﻿var baseUrl = "";
var mainContaintHeight = 550;

$(function () {
    globalInit();
});

//页面初始化
function globalInit()
{
    window.onresize = setHeight;
    setHeight();

    $('#leftnavdiv .nav-header').one('click', function () {
        OpenUp(this);
    });

    $('#leftnavdiv .nav-list .nav-header:first').click();

    $('#leftnavdiv .nav-list a').bind('click', function (e) {
        e.preventDefault();
        OpenContent(this);
    });

    $('.datetime').live("focus", function () {
        $(this).datepicker();
    });

    $("input[name='Keyword'][type='text']")
        .die("keydown")
        .live("keydown", function (event) {
            if (event.which == 13) {
                $(this).next().click();
                return false;
            }
    });

    $('.SearchContent .pagedlist a')
        .live("click", function (e) {
        var url = this.href;
        if (url.length > 5) {
            GetAJAX(url, {}, function (r) {
                $('.SearchContent').html(r);
            });
            e.preventDefault();
        }
    });
}

//-------------查询与表单-------------------------

//提交新建或者修改页面
function FormSave(form,callback) {
    if ($(form).valid()) {
        var data = $(form).serialize();
        var url = $(form).attr('action');
        $.post(url, data, function (result, textStatus, jqXHR) {
            if (result.Result) {
                $(form).parents('.modal').modal('hide');

                if (callback == null) {
                    //刷新
                    RefreshSearchContent();
                } else {
                    callback();
                }

            } else
                alert(result.MSG);
        });
    }
}

//全选
function CheckAll(container) {
    var value = $('#checkAll', container)[0].checked;
    $("input[name=selected]", container).each(function (i) {
        this.checked = value;
    });
}

//搜索
function Search(el) {
    var url = $(el).attr('url');
    var searchForm = $(el).parents('form')[0];
    if (typeof (url) == 'undefined' || url.length == 0) {
        url = $(searchForm).attr('action');
    }

    var data = $(searchForm).serialize() + "&rand=" + Math.random();
    var UpateID = $(searchForm).attr('update-target') || '.SearchContent';

    GetAJAX(url, data, function (r) {
        $(UpateID).html(r);
    });
}

//刷新列表
function RefreshSearchContent(container) {
    var refUrl = $(".SearchContent .pagedlist a.active", container).attr('href');
    if (refUrl == undefined || refUrl.length < 2) {
        refUrl = $(".SearchContent table").attr('targeturl');
    }
    if (refUrl && refUrl.length > 2) {
        $.get(refUrl, { rand: Math.random() }, function (refList) {
            $('.SearchContent', container).html(refList);
        });
    }
}


//-----------------------弹窗-----------------------
//提示信息
function MsgAlert(msg) {
    bootbox.dialog(msg, {
        "label": "确定",
        "icon": 'icon-ok',
        "callback": null
    }, {
        "onEscape": null,
        "classes": "alertModal"
    });
}

//弹窗
function Dialog(html, buttons, options) {
    options = options || { "classes": "winModal" };
    options.classes = options.classes || "winModal";
    bootbox.dialog(html, buttons, options);
}

//确认页面
function MsgConfirm() {
    if (arguments && arguments.length > 0) {
        var str = "确定此操作?";
        var cb = null;
        if (arguments.length == 1) {
            cb = arguments[0];
        } else if (arguments.length == 2) {
            str = arguments[1] || "确定此操作?";
            cb = arguments[0];
        }
        return bootbox.dialog(str, [{
            "label": "取消",
            "icon": "icon-remove",
            "callback": function () {
                if (typeof cb == 'function') {
                    cb(false);
                }
            }
        }, {
            "label": "确认",
            "icon": 'icon-ok',
            "callback": function () {
                if (typeof cb == 'function') {
                    cb(true);
                }
            }
        }],
    {
        "onEscape": function () {
            if (typeof cb == 'function') {
                cb(false);
            }
        },
        "classes": "alertModal"
    });

    } else
        return false;
}

//打开详细页面
function ShowDetails(el) {
    var title = $(el).text();
    var url = $(el).attr('href');
    GetAJAX(url, { rand: Math.random() }, function (r) {
        bootbox.dialog(r, [], { header: title, classes: "winModal" });

    });
}

//打开新建或者修改页面
function ShowCreateOrEdit(el) {
    var url = $(el).attr('href');
    var title = $.trim($(el).text());
    ShowDialogFormEdit(url, { rand: Math.random() }, title);
}

function ShowDialogFormEdit(url, data, title) {
    GetAJAX(url, data, function (r) {
        var dialog = bootbox.dialog(r, [
        {
            "label": "取消",
            "icon": "icon-remove",
            "callback": function () { }
        }, {
            "label": "保存",
            "class": "btn-primary",
            "icon": 'icon-ok',
            "callback": function (ele) {
                var form = $(ele).parent().prev().find('form');
                FormSave(form);
                return false;
            }
        }],
        { header: title, classes: "winModal" });
        BindFormEvent();
    });
    return false;
}

//刷新弹窗
function ShowRefresh(el, container) {
    var url = $(el).attr('href');
    var title = $.trim($(el).text());
    GetAJAX(url, { rand: Math.random() }, function (r) {
        bootbox.dialog(r, [
        {
            "label": "确定",
            "class": "btn-primary",
            "icon": 'icon-ok',
            "callback": function () { RefreshSearchContent(container); }
        }],
        { header: title, classes: "winModal" });
        BindFormEvent();
    });
}

//打开选择页面,name=selected
function ShowSelect(url, callback) {
    var title = '请选择';
    GetAJAX(url, { rand: Math.random() }, function (r) {
        bootbox.dialog(r, [{
            "label": "取消",
            "icon": "icon-remove",
            "callback": function () { }
        }, {
            "label": "选择",
            "icon": 'icon-ok',
            "class": "btn-primary",
            "callback": function (ele) {
                var selected = $(ele).parent().prev().find('input[name=selected]:checked');
                if (typeof callback == 'function' && selected.length > 0)
                    callback(selected);
            }
        }],
        { header: title, classes: "winModal" });

    });
    return false;
}

//-----------------------一般方法------------------------------

//设置高度
function setHeight() {
    mainContaintHeight = document.documentElement.clientHeight - $('#head').height();
    $("#MainContent").width(document.documentElement.clientWidth - 290);
    $("#leftnavdiv").height(mainContaintHeight);
    $(".dv-nav").height(mainContaintHeight - 30);
    $('#MainContent').height(mainContaintHeight - 20);
}


//点击后3秒才能下一次点击
function disabledClick(el) {
    $(el).prop('disabled', true);
    setTimeout(function () { $(el).prop('disabled', false); }, 3000);
}

//替代内容区域
function OpenContent(el) {
    var url = $(el).attr('href');
    var replaceID = "MainContent";
    GetAJAX(url, {}, function (msg) {
        $('#' + replaceID).html(msg);
    });

    $('#leftnavdiv ul li').removeClass('active');
    $(el).parent().addClass('active');
}

//绑定表单事件
function BindFormEvent() {
    jQuery.validator.unobtrusive.parse('form');
}


//显示提示
function ShowNotice(h) {
    if ($('#dvnotice').length > 0) {
        $('#dvnotice').remove();
    }

    var html = $('<div class="well alert alert-error" id="dvnotice"><button type="button" class="close" data-dismiss="alert">×</button></div>').append(h);
    $('body').append(html);
}

//隐藏提示
function HideNotice() {
    if ($('#dvnotice').length > 0) {
        $('#dvnotice').remove();
    }
}

//高级搜索
function ShowAdvancedSearch(el) {
    //默认不显示
    var form = $(el).parents('form');
    var _AdvancedSearch = form.find('#AdvancedSearch');

    if (_AdvancedSearch.length > 0) {
        var isAdvancedSearch = (_AdvancedSearch.val() == "True");
        if (isAdvancedSearch) {
            $('.advanced-search', form).hide();
            _AdvancedSearch.val('False');
            $(el).text("高级搜索");
        } else {
            $('.advanced-search', form).show();
            _AdvancedSearch.val('True');
            $(el).text("简单搜索");
        }
    }
}

//快捷操作
function ShortcutLink(el, call) {
    var text = $.trim($(el).text());
    text = "确定" + text + "吗？";
    if (confirm(text)) {
        var url = $(el).attr('href');
        //event.preventDefault();
        $.post(url, function (r) {
            if (r.Result) {
                RefreshSearchContent();
                if (call && typeof call == "function") {
                    call(el);
                }
            } else
                alert(r.MSG);
        });
    }
}

//Ajax开始方法
function StartLoading() {
    if ($('#loading').length == 0) {
        var html = '<div class="well" id="loading">加载中，请稍等...... <img src="' + baseUrl + '/Content/img/loading.gif" alt="loading.." /></div>';
        $('body').append(html);
    } else {
        $('#loading').show();
    }
}

//Ajax结束方法
function EndLoading() {
    if ($('#loading').length > 0) {
        $('#loading').hide();
    }
}

//点击后操作
function ListClickAfter(el) {
    $(el).css('backgroud-color', 'yellow');
}

//删除本行
function DeleteTr(el) {
    $(el).parents("tr").remove();
}

//展开
function OpenUp(el) {
    var key = $(el).attr('grouphead');
    $('li[group="' + key + '"]').show();
    $('.imgAdd', el).attr('src', baseUrl + '/Content/img/jian.png');
    $(el).one('click', function () {
        PackUp(this);
    });
}

//收缩
function PackUp(el) {
    var key = $(el).attr('grouphead');
    $('li[group="' + key + '"]').hide();
    $('.imgAdd', el).attr('src', baseUrl + '/Content/img/jia.png')
    $(el).one('click', function () {
        OpenUp(this);
    });
}

//选择文件
function SelectIt(el) {
    var value = $(el).attr('value');
    $($(el).parents('.btn-group')[0]).find('input:text').val(value);
}

//----------------------工具----------------------

//ajax封装
function GetAJAX(url, data, call) {
    $.ajax({
        url: url,
        data: data,
        success: call,
        cache: false,
        beforeSend: function () {
            StartLoading();
        },
        complete: function () {
            EndLoading();
        },
        error: function (rep) {
            alert("错误！");
        }
    });
}

//上传文件
function Upload(url) {
    $.ajaxFileUpload({
        url: url,
        secureuri: false,
        fileElementId: 'upload',
        dataType: 'json',
        data: {//加入的文本参数  
            //"fileDes": $("#filedes").val()
        },
        beforeSend: function () {
            $('#fileloading').show();
        },
        complete: function () {
            $('#fileloading').hide();
        },
        success: function (data, status) {
            if (data.Result) {
                $('#uploadresult').text("上传成功");
                if ($('input[name=FileName]').length > 0) {
                    var val = $('input[name=FileName]').val();
                    val += data.MSG + ";";
                    $('input[name=FileName]').val(val);
                }
                if ($('#fileList').length > 0) {
                    var name = data.MSG.substring(data.MSG.indexOf('_') + 1);
                    $('#fileList').append('<tr><td>' + name + '</td></tr>');
                }
            } else {
                alert(data.MSG);
            }
        },
        error: function (data, status, e) {
            alert('上传错误：' + e);
        }
    });
    return false;
}

//项目
function ToSuccess(msg) {
    var url = baseUrl + '/Home/Success';
    window.location.href = url + '?msg=' + msg;
}

//转到成功页面
function ToError(msg) {
    var url = baseUrl + '/Home/Error';
    window.location.href = url + '?msg=' + msg;
}

//返回首页
function GoHome() {
    var url = baseUrl + '/';
    GetAJAX(url, { rand: Math.random() }, function (msg) {
        $('#MainContent').html(msg);
    });
}

//时间扩展
Date.prototype.format = function (format) {
    /*
    * eg:format="yyyy-MM-dd hh:mm:ss";
    */
    var o = {
        "M+": this.getMonth() + 1,  //month
        "d+": this.getDate(),     //day
        "h+": this.getHours(),    //hour
        "m+": this.getMinutes(),  //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}

//时间格式转换
function ConertJsonTimeAndFormat(jsonTime, format) {
    return new Date(eval(jsonTime.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"))).format(format);
}

//保留两位小数   
//功能：将浮点数四舍五入，取小数点后2位  
function toDecimal(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return;
    }
    f = Math.round(x * 100) / 100;
    return f;
}